import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../common/api_service.dart'; // 导入 ApiService 类
import 'package:firebase_analytics/firebase_analytics.dart';
import '../common/loading_spinner.dart'; // 导入公共组件
import 'package:cached_network_image/cached_network_image.dart'; //网络图片缓存到本地
import '../message.dart';
import 'dart:math';
import 'package:screenshot/screenshot.dart';
import 'dart:typed_data';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:share_plus/share_plus.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:in_app_review/in_app_review.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import '../ads/consent_manager.dart';
import '../ads/ads_unit_id.dart';


class DiyPage extends StatefulWidget {
  const DiyPage({
    super.key,
  });

  @override
  State<DiyPage> createState() => _DiyPageState();
}

class _DiyPageState extends State<DiyPage> {
  bool isMember = false;

  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  ScreenshotController screenshotController = ScreenshotController();
  final InAppReview inAppReview = InAppReview.instance;

  bool _isRewardAdLoaded = false;
  final _consentManager = ConsentManager.instance;
  RewardedAd? _rewardedAd;

  String curSubIndex = 'good-morning';
  bool isLoading = false;
  List categoryList = []; // 所有类别数据
  Map curCategoryDataList = {}; // 当前类别数据
  int imgId = 0; // 当前图片id
  int stickerId = 0;
  List messageList = []; //文本信息
  final controller = ScrollController();
  int textIndex = 9999;
  String curText = 'Haga clic para ingresar texto';
  String cutFont = 'Lobster'; // 默认字体
  double curFontSize = 30;
  bool isBold= false;
  bool isItalic = false;
  bool isUnderline = false;
  bool isPainter = true;
  bool isStickerPainter = true;
  final TextEditingController _controller = TextEditingController();
  void fetchData() async {
    setState(() {
      isLoading = true;
    });
    try {
      String url = 'https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/json/diy.json'; // 替换为你的 URL
      List<dynamic> jsonData = await ApiService.fetchJsonData(url);

      var curCategoryData = jsonData[0]['list'].firstWhere((item) => item['slug'] == curSubIndex, orElse: () => null);

      setState(() {
        categoryList = jsonData[0]['list'];
        curCategoryDataList = curCategoryData;
      });

      // print('---');
      // print(curCategoryDataList);
    } catch (e) {
      // print(e);
    }
  }



  void _loadRewardAd() async {
    // int adStatus = await _getAdStatus();
    // // print(adStatus);
    // if (adStatus != 1) {
    //   return;
    // }

    // Only load an ad if the Mobile Ads SDK has gathered consent aligned with
    // the app's configured messages.
    var canRequestAds = await _consentManager.canRequestAds();
    if (!canRequestAds) {
      return;
    }

    RewardedAd.load(
      adUnitId: AdsUnitId.rewardAdUnitId,
      request: const AdRequest(),
      rewardedAdLoadCallback: RewardedAdLoadCallback(onAdLoaded: (ad) {
        ad.fullScreenContentCallback = FullScreenContentCallback(
            // Called when the ad showed the full screen content.
            onAdShowedFullScreenContent: (ad) {},
            // Called when an impression occurs on the ad.
            onAdImpression: (ad) {},
            // Called when the ad failed to show full screen content.
            onAdFailedToShowFullScreenContent: (ad, err) {
              ad.dispose();
              _loadRewardAd();
              setState(() {
                _isRewardAdLoaded = false; // 广告未加载
              });
              
            },
            // Called when the ad dismissed full screen content.
            onAdDismissedFullScreenContent: (ad) {
              ad.dispose();
              _loadRewardAd();
              setState(() {
                _isRewardAdLoaded = false; // 广告未加载
              });
            },
            // Called when a click is recorded for an ad.
            onAdClicked: (ad) {});

        // Keep a reference to the ad so you can show it later.
        _rewardedAd = ad;
        // _isRewardAdLoaded = true;

        setState(() {
          _isRewardAdLoaded = true;
          // _showWatchVideoButton = true;
        });
      }, onAdFailedToLoad: (LoadAdError error) {
        // ignore: avoid_print
        print('RewardedAd failed to load: $error');
        _loadRewardAd();
        setState(() {
          _isRewardAdLoaded = false; // 广告未加载
        });
      }));
  }

  @override
  void initState() {
    super.initState();
    _logScreenView();

    _loadRewardAd();
    fetchData();

    getMessageList(curSubIndex);
  }

  

  @override
  void dispose() {
    _rewardedAd?.dispose();
    super.dispose();
  }

  void getMessageList(String curSubIndex) {
    var listItem = messageDatas.firstWhere((item) => item['slug'] == curSubIndex, orElse: () => null);
    if (listItem != null) {
      setState(() {
        messageList = listItem['list'];
      });
    }

    // print(messageList);

    // return messageList;
  }

  Future<void> _logScreenView() async {
    await analytics.logScreenView(
      screenName: 'DIY Page ES',
      screenClass: 'DIYPage_ES',
    );
    // setMessage('setCurrentScreen succeeded');
  }

  Future<Database> getDatabase() async {
    return openDatabase(
      join(await getDatabasesPath(), 'images.db'),
      onCreate: (db, version) {
        return db.execute(
          'CREATE TABLE images(id INTEGER PRIMARY KEY, image BLOB)',
        );
      },
      version: 1,
    );
  }

  Future<void> saveImageToDatabase(byteArray) async {
    final db = await getDatabase();
    Uint8List bytes = Uint8List.fromList(byteArray);

    await db.insert(
      'images',
      {'image': bytes},
      conflictAlgorithm: ConflictAlgorithm.replace,
    );

    // print('Image saved to SQLite');
  }

  Future<void> shareImage(List<int> bytes) async {
    final tempDir = await getTemporaryDirectory();
    final tempFile = File('${tempDir.path}/shared_image.jpg');
    await tempFile.writeAsBytes(bytes);
    await Share.shareXFiles(
      [XFile(tempFile.path)],
      text: 'Esta es la tarjeta que diseñé para ti yo mismo. ¿Te gusta?',
      sharePositionOrigin: const Rect.fromLTWH(0, 0, 100, 100),
      subject: 'Compartiendo mi tarjeta hecha a mano',
      // chooserTitle: 'Share via',
    );
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;


    
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(60),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                offset: const Offset(0, 2),
                blurRadius: 6.0,
              ),
            ],
          ),
          child: AppBar(
            backgroundColor: Colors.white,
            title: const Text(
              'DIY',
              style: TextStyle(fontFamily: 'OpenSans', color: Colors.black, fontWeight: FontWeight.bold),
            ),
            actions: [

              IconButton(
                icon: const Icon(CupertinoIcons.star),
                onPressed: () => {inAppReview.openStoreListing(appStoreId: '6740426686')},
                // child: const Icon(CupertinoIcons.star),
              ),
            ],
          ),
        ),
      ),
      body: categoryList.isEmpty ? const LoadingSpinner() : InkWell(
        onTap: () {
          setState(() {
            isStickerPainter = false;
            isPainter = false;
          });
        },
        child: Column(
          children: [
            imgId != 0 ? 
            Screenshot(
              controller: screenshotController,
              child: Container(
                padding: const EdgeInsets.only(top: 16, left: 16, right: 16),
                child: Center(
                  child: SizedBox(
                    height: width,
                    child: Stack(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(3.0),
                          child: CachedNetworkImage(
                            width: width-32,
                            height: width-32,
                            imageUrl: "https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/images-origin/$curSubIndex/$imgId.webp??x-oss-process=image/resize,p_512",
                            placeholder: (context, url) => const LoadingSpinner(), // 占位图
                            errorWidget: (context, url, error) => const Icon(Icons.error), // 错误图标
                            fit: BoxFit.cover,
                          )
                        ),
                        
                        Positioned(
                          left: 16,
                          right: 16,
                          top: 100,
                          bottom: 16,
                          child: Center(
                            child: CustomPaint(
                              size: Size(width-64, 200), // 设置自定义绘制的大小
                              painter: isPainter ? DashedBorderPainter(borderColor: Colors.white) : null,
                              child: InkWell(
                                onTap: () {
                                  setState(() {
                                    isPainter = true;
                                  });
                                  _controller.text = curText;
                                  showMessageDialog(context);
                                },
                                child: SizedBox(
                                  width: width-64,
                                  height: 200,
                                  child: Center(
                                    child: Text(curText, style: TextStyle(color: Colors.white, fontSize: curFontSize, fontFamily: cutFont, fontWeight: isBold ? FontWeight.bold : FontWeight.normal, fontStyle: isItalic ? FontStyle.italic : FontStyle.normal, decoration: isUnderline ? TextDecoration.underline : TextDecoration.none, decorationColor: Colors.white,),  textAlign: TextAlign.center,),
                                  ) ,
                                ),
                              )  
                            )
                          )
                        ),
                        
                        Positioned(
                          top: 32,
                          left: 16,
                          right: 16,
                          height: 100,
                          child: Center(
                            child: CustomPaint(
                              size: const Size(100, 100), // 设置自定义绘制的大小
                              painter: isStickerPainter ? DashedBorderPainter(borderColor: Colors.white) : null,
                              child: InkWell(
                                onTap: () {
                                  setState(() {
                                    isStickerPainter = true;
                                  });
                                  // _controller.text = curText;
                                  showStickerDialog(context);
                                },
                                child: stickerId == 0 ? const SizedBox(
                                  width: 100,
                                  height: 100,
                                  child: Center(
                                    child: Text('Haga clic para añadir stickers', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), textAlign: TextAlign.center,),
                                  )
                                ) : CachedNetworkImage(
                                  imageUrl: "https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/images-origin/$curSubIndex/sticker/$stickerId.webp??x-oss-process=image/resize,p_200",
                                  placeholder: (context, url) => const LoadingSpinner(), // 占位图
                                  errorWidget: (context, url, error) => const Icon(Icons.error), // 错误图标
                                  fit: BoxFit.contain,
                                ),
                              )  
                            ),
                          ),
                        )
                      ],
                    ) ,
                  ),
                ),
              )
            ):
            InkWell(
              onTap: (){
                showbgDialog(context);
              },
              child: Container(
                margin: const EdgeInsets.only(bottom: 32),
                padding: const EdgeInsets.only(top: 16, left: 16, right: 16),
                child: CustomPaint(
                  size: Size(width-32, width-32), // 设置自定义绘制的大小
                  painter: DashedBorderPainter(borderColor: Colors.black),
                  child: Container(
                    width: width-32,
                    height: width-32,
                    padding: const EdgeInsets.only(left: 48, right: 48),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SizedBox(
                          width: 40,
                          height: 40,
                          child: Image.asset('images/image.png'),
                        ),
                        // Icon(CupertinoIcons.add_circled_solid, color: Colors.black, size: 36,),
                        const SizedBox(height: 8,),
                        const Text('Haga clic para seleccionar imágenes hermosas', style: TextStyle(fontFamily: 'OpenSans', color: Colors.black87),textAlign: TextAlign.center,)
                      ],
                      
                    ),
                  ) ,
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(left: 16, right: 16,),
              child: InkWell(
                onTap: () {
                  screenshotController.capture(delay: const Duration(milliseconds: 10)).then((capturedImage) async {
                    if(capturedImage == null){
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('Todo está bien, pero encontramos un pequeño problema. ¡Por favor, inténtalo de nuevo más tarde!', style: TextStyle(fontSize: 16),),
                          duration: Duration(seconds: 2),
                          backgroundColor: Colors.green,
                        ),
                      );
                    }else{
                      if(_isRewardAdLoaded && _rewardedAd != null){
                        _rewardedAd?.show(onUserEarnedReward:
                            (AdWithoutView ad, RewardItem rewardItem) {
                          
                            saveImageToDatabase(capturedImage);
                            final result = ImageGallerySaver.saveImage(capturedImage);
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('¡Guardado con éxito en la galería!', style: TextStyle(fontSize: 16),),
                                duration: Duration(seconds: 2),
                                backgroundColor: Colors.green,
                              ),
                            );
                        });
                      }else{
                        saveImageToDatabase(capturedImage);
                        final result = await ImageGallerySaver.saveImage(capturedImage);
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(
                            content: Text('¡Guardado con éxito en la galería!', style: TextStyle(fontSize: 16),),
                            duration: Duration(seconds: 2),
                            backgroundColor: Colors.green,
                          ),
                        );
                      }
                      
                      // print(capturedImage);
                      
                      // shareImage(capturedImage);
                    }
                  }).catchError((onError) {
                    // print('----');
                    // print(onError);
                  });
                },
                child: Stack(
                  children: [ 
                    Container(
                      height: 64,
                      margin: const EdgeInsets.only(left: 24, right: 24, top: 8),
                      decoration: BoxDecoration(
                        color: const Color.fromARGB(255, 215, 31, 39),
                        borderRadius: BorderRadius.circular(32)
                      ),
                      child: const Center(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(CupertinoIcons.cloud_download, color: Colors.white,),
                            SizedBox(width: 6,),
                            Text(
                              'Guardar en la galería',
                              style: TextStyle(
                                color: Colors.white,
                                // fontWeight: FontWeight.w600,
                                fontSize: 20,
                                fontFamily: 'OpenSans',
                              ),
                            )
                          ],
                        ) ,
                      ),

                    ),

                    if(_isRewardAdLoaded)
                      Positioned(
                        right: 16,
                        top: 0,
                        child: Container(
                          width: 36,
                          height: 30,
                          padding: const EdgeInsets.all(5),
                          decoration: BoxDecoration(
                            color: const Color.fromARGB(255, 252, 229, 13),
                            borderRadius: BorderRadius.circular(15),
                            // image: DecorationImage(
                            //   image: AssetImage('images/ad.png'))
                          ),
                          child: Container(
                            decoration: const BoxDecoration(
                            
                            image: DecorationImage(
                              image: AssetImage('images/ad.png'))
                          ),
                          ),
                        )
                      )
                  ]
                )
              ),
            ),
            Container(
              margin: const EdgeInsets.only(left: 16, right: 16, top: 16),
              child: InkWell(
                onTap: () {
                  screenshotController.capture(delay: const Duration(milliseconds: 10)).then((capturedImage) async {
                    if(capturedImage == null){
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('Todo está bien, pero encontramos un pequeño problema. ¡Por favor, inténtalo de nuevo más tarde!', style: TextStyle(fontSize: 16),),
                          duration: Duration(seconds: 2),
                          backgroundColor: Colors.green,
                        ),
                      );
                    }else{
                      if(_isRewardAdLoaded && _rewardedAd != null){

                        // 设置全屏内容回调
                        _rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
                          onAdShowedFullScreenContent: (ad) {
                            // 广告展示时的处理逻辑
                          },
                          onAdImpression: (ad) {
                            // 广告印象时的处理逻辑
                          },
                          onAdFailedToShowFullScreenContent: (ad, err) {
                            ad.dispose();
                            _loadRewardAd(); // 重新加载广告
                          },
                          onAdDismissedFullScreenContent: (ad) {
                            ad.dispose();
                            _loadRewardAd(); // 重新加载广告

                            saveImageToDatabase(capturedImage);
                            shareImage(capturedImage);
                          },
                          onAdClicked: (ad) {
                            // 广告被点击时的处理逻辑
                          },
                        );

                        _rewardedAd?.show(onUserEarnedReward:
                        (AdWithoutView ad, RewardItem rewardItem) {
                        
                        });

                        
                      }else{
                        saveImageToDatabase(capturedImage);
                        shareImage(capturedImage);
                      }

                      
                      
                    }
                  }).catchError((onError) {
                    // print('----');
                    // print(onError);
                  });
                },
                child: Stack(
                  children: [
                    Container(
                      height: 64,
                      margin: const EdgeInsets.only(left: 24, right: 24, top: 8),
                      decoration: BoxDecoration(
                          color: const Color.fromARGB(255, 215, 31, 39),
                          borderRadius: BorderRadius.circular(32)),
                      child: const Center(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(CupertinoIcons.share, color: Colors.white,),
                            SizedBox(width: 6,),
                            Text(
                              'Compartir con amigos',
                              style: TextStyle(
                                color: Colors.white,
                                // fontWeight: FontWeight.w600,
                                fontSize: 20,
                                fontFamily: 'OpenSans',
                              ),
                            )
                          ],
                        ) ,
                      ),
                    ),
                    if(_isRewardAdLoaded)
                      Positioned(
                        right: 16,
                        top: 0,
                        child: Container(
                          width: 36,
                          height: 30,
                          padding: const EdgeInsets.all(5),
                          decoration: BoxDecoration(
                            color: const Color.fromARGB(255, 252, 229, 13),
                            borderRadius: BorderRadius.circular(15),
                            // image: DecorationImage(
                            //   image: AssetImage('images/ad.png'))
                          ),
                          child: Container(
                            decoration: const BoxDecoration(
                            
                            image: DecorationImage(
                              image: AssetImage('images/ad.png'))
                          ),
                          ),
                        )
                      )
                  ],
                ) ,
              ),
            ),
            const Spacer(),
            
            Container(
              // padding: const EdgeInsets.only(top: 16),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    offset: const Offset(0, 2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: SafeArea(
                child: Row(
                  children: [
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          showbgDialog(context);
                        },
                        child: const Column(
                          children: [
                            SizedBox(height: 16,),
                            Icon(CupertinoIcons.photo, color: Colors.black,),
                            Text('Imagen', style: TextStyle(fontFamily: 'OpenSans', color: Colors.black),)
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          showStickerDialog(context);
                        },
                        child: const Column(
                          children: [
                            SizedBox(height: 16,),
                            Icon(CupertinoIcons.brightness, color: Colors.black,),
                            Text('Stickers', style: TextStyle(fontFamily: 'OpenSans', color: Colors.black),)
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          showMessageDialog(context);
                        },
                        child: const Column(
                          children: [
                            SizedBox(height: 16,),
                            Icon(CupertinoIcons.bubble_left_bubble_right, color: Colors.black,),
                            Text('Mensajes', style: TextStyle(fontFamily: 'OpenSans', color: Colors.black),)
                          ],
                        ),
                      ),
                    ),
                    
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          if(_isRewardAdLoaded && _rewardedAd != null){
                            _rewardedAd?.show(onUserEarnedReward:
                            (AdWithoutView ad, RewardItem rewardItem) {
                              showStyleDialog(context);
                            });
                          }else{
                            showStyleDialog(context);
                          }
                          
                        },
                        child:
                            Container(
                              // color: Colors.blue,
                              child: Center(
                                child: Stack(
                                  children: [
                                    Container(
                                      padding: const EdgeInsets.only(left: 10, right: 10),
                                      child: const Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          SizedBox(height: 16,),
                                          Icon(CupertinoIcons.textformat, color: Colors.black,),
                                          Text('Estilo', style: TextStyle(fontFamily: 'OpenSans', color: Colors.black),)
                                        ],
                                      ),
                                    ) ,
                                    if(_isRewardAdLoaded)
                                      Positioned(
                                        right: 0,
                                        top: 0,
                                        child: Container(
                                          width: 24,
                                          height: 24,
                                          padding: const EdgeInsets.all(4),
                                          decoration: BoxDecoration(
                                            color: const Color.fromARGB(255, 252, 229, 13),
                                            borderRadius: BorderRadius.circular(15),
                                            // image: DecorationImage(
                                            //   image: AssetImage('images/ad.png'))
                                          ),
                                          child: Container(
                                            decoration: const BoxDecoration(
                                            
                                            image: DecorationImage(
                                              image: AssetImage('images/ad.png'))
                                          ),
                                          ),
                                        )
                                      )
                                  ],
                                ),
                              )  ,
                            )
                            ,
                            
                         
                      ),
                    )
                  ]
                )
              ),
            )
            
          ],
        )
      ),
    );
  }

  void showStickerDialog(BuildContext context) {
    double height = MediaQuery.of(context).size.height; 
    double width = MediaQuery.of(context).size.width;

    showModalBottomSheet(
      isScrollControlled: true,
      backgroundColor: const Color.fromARGB(0, 153, 153, 153),
      barrierColor: Colors.transparent,
      context: context,
      builder: (BuildContext context) {
        return  
          Container(
            height: height * .5,
            width: width,
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.3),
                  offset: const Offset(0, 3),
                  blurRadius: 10.0,
                ),
              ],
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              )
            ),
            
            child: SafeArea(child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    padding: const EdgeInsets.only(left: 16, right: 16, top: 12),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text('Stickers'),
                        InkWell(
                          onTap: () {
                            // setState(() {
                            //   isStickerPainter = false;
                            //   (context as Element).markNeedsBuild();
                            // });
                            Navigator.pop(context);
                          },
                          child: const Icon(CupertinoIcons.check_mark, color: Colors.black,),
                        )
                      ],
                    ),
                  ),
                  if(curCategoryDataList['sticker'] != null)
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(left: 16, right: 16),
                        child: SingleChildScrollView(
                          controller: controller,
                          child: GridView.builder(
                            shrinkWrap: true, // 使 GridView 的高度适应内容
                            physics: const NeverScrollableScrollPhysics(), // 禁用 GridView 的滚动
                            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 4, // 每行放置 4 张图片
                              childAspectRatio: 1, // 宽高比
                              crossAxisSpacing: 8, // 交叉轴间距
                              mainAxisSpacing: 8, // 主轴间距
                            ),
                            itemCount: curCategoryDataList['sticker'].length,
                            itemBuilder: (context, index) {
                              return InkWell(
                                onTap: () {
                                  setState(() {
                                    stickerId = curCategoryDataList['sticker'][index];
                                  });
                                },
                                child: Container(
                                  width: 100,
                                  height: 100,
                                  padding: const EdgeInsets.only(left: 8, right: 8),
                                  child: CachedNetworkImage(
                                    imageUrl: "https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/images-origin/$curSubIndex/sticker/${curCategoryDataList['sticker'][index]}.webp",
                                    placeholder: (context, url) => const LoadingSpinner(), // 占位图
                                    errorWidget: (context, url, error) => const Icon(Icons.error), // 错误图标
                                    fit: BoxFit.contain,
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
                      ) 
                    ),
                ],
              ),
            ),
          )
        );
      },
    );
  }


  void showStyleDialog(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;

    showModalBottomSheet(
      isScrollControlled: true,
      backgroundColor: const Color.fromARGB(0, 153, 153, 153),
      barrierColor: Colors.transparent,
      context: context,
      builder: (BuildContext context) {
        return  
          Container(
            height: 400,
            width: width,
            // padding: const EdgeInsets.only(top: 12),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.3),
                  offset: const Offset(0, 3),
                  blurRadius: 10.0,
                ),
              ],
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              )
            ),
            
            child: SafeArea(
              child: Container(
                padding: const EdgeInsets.only(left: 16, top: 16),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text('FONT'),
                        Container(
                          margin: const EdgeInsets.only(right: 16),
                          child: InkWell(
                            onTap: () {
                              // print('000');
                              // setState(() {

                              //   isPainter = false;
                              //   (context as Element).markNeedsBuild();
                              // });
                              // print(isPainter);
                              Navigator.pop(context);
                            },
                            child: const Icon(CupertinoIcons.check_mark, color: Colors.black,),
                          ),
                        ),
                      ],
                    ),
                    
                    const SizedBox(height: 6,),
                    FontSelectionRow(
                      onFontSelected: (String font) {
                        setState(() {
                          cutFont = font; // 更新字体
                          (context as Element).markNeedsBuild();
                        });
                      },
                      selectedFont: cutFont, // 传递当前选中的字体
                    ),
                    const SizedBox(height: 32,),
                    const Text('TEXT SIZE'),
                    Row(
                      children: [
                        // 左侧数字
                        const Text('16', style: TextStyle(fontSize: 14)),
                        Expanded(
                          child: Slider(
                            value: curFontSize,
                            min: 16,
                            max: 50,
                            divisions: 34, // 使滑块有34个分段
                            inactiveColor: const Color.fromRGBO(0, 0, 0, .2),
                            activeColor: Colors.black87,
                            label: curFontSize.round().toString(),
                            onChanged: (double newValue) {
                              setState(() {
                                curFontSize = newValue; // 更新字体大小
                                (context as Element).markNeedsBuild();
                              });
                            },
                          ),
                        ),
                        // 右侧数字
                        const Text('50', style: TextStyle(fontSize: 14)),
                        const SizedBox(width: 16,),
                        
                      ],
                    ),
                    const SizedBox(height: 32,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        InkWell(
                          onTap: () {
                            
                            setState(() {
                              isBold = false;
                              isItalic = false;
                              isUnderline = false;
                              (context as Element).markNeedsBuild();
                            });
                          },
                          child: Container(
                            width: 40,
                            height: 40,
                            decoration: const BoxDecoration(
                              color: Color.fromRGBO(0, 0, 0, .08),
                              borderRadius: BorderRadius.all(Radius.circular(4)),
                            ),
                            child: const Icon(CupertinoIcons.slash_circle, color: Colors.black87, size: 20,)
                          )
                        ),
                        InkWell(
                          onTap: () {
                            setState(() {
                              isBold = !isBold;
                              (context as Element).markNeedsBuild();
                            });
                          },
                          child: Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              color: isBold ? Colors.black87 : const Color.fromRGBO(0, 0, 0, .08),
                              borderRadius: const BorderRadius.all(Radius.circular(4)),
                            ),
                            child: Icon(CupertinoIcons.bold, color: isBold ? Colors.white : Colors.black87, size: 20,)
                          )
                        ),
                        InkWell(
                          onTap: () {
                            setState(() {
                              isItalic = !isItalic;
                              (context as Element).markNeedsBuild();
                            });
                            
                          },
                          child: Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              color: isItalic ? Colors.black87 : const Color.fromRGBO(0, 0, 0, .08),
                              borderRadius: const BorderRadius.all(Radius.circular(4)),
                            ),
                            child: Icon(CupertinoIcons.italic, color: isItalic ? Colors.white : Colors.black87, size: 20,)
                          )
                        ),
                        InkWell(
                          onTap: () {
                            setState(() {
                              isUnderline = !isUnderline;
                              (context as Element).markNeedsBuild();
                            });
                            
                          },
                          child: Container(
                            width: 40,
                            height: 40,
                            margin: const EdgeInsets.only(right: 16),
                            decoration: BoxDecoration(
                              color: isUnderline ? Colors.black87 : const Color.fromRGBO(0, 0, 0, .08),
                              borderRadius: const BorderRadius.all(Radius.circular(4)),
                            ),
                            child: Icon(CupertinoIcons.underline, color: isUnderline ? Colors.white : Colors.black87, size: 20,)
                          )
                        ),
                        
                      ]
                    )
                  ],
                ),
              ) 
            )
          );
      }
    );
  }

  void showMessageDialog(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;

    void _clearInput() {
      _controller.clear();
    }

    showModalBottomSheet(
      isScrollControlled: true,
      backgroundColor: const Color.fromARGB(0, 153, 153, 153),
      barrierColor: Colors.transparent,
      context: context,
      builder: (BuildContext context) {
        return  
          Container(
            height: height*.5,
            width: width,
            // padding: const EdgeInsets.only(top: 12),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.3),
                  offset: const Offset(0, 3),
                  blurRadius: 10.0,
                ),
              ],
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              )
            ),
            
            child: SafeArea(
               child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  const SizedBox(height: 16,),
                  // Container(
                  //   padding: const EdgeInsets.only(left: 16, right: 16, top: 12),
                  //   child: Row(
                  //     children: [
                  //       Text('Mensajes'),
                  //       const Spacer(),
                  //       InkWell(
                  //       onTap: () {
                  //         Navigator.pop(context);
                  //       },
                  //       child: const Icon(CupertinoIcons.check_mark),
                  //     )
                  //     ],
                  //   ),
                  // ),
                  Row(
                    children: [
                      Expanded(
                        child: Stack(
                          children: [
                            Container(
                              // height: 48.0, // 设置高度
                              margin: const EdgeInsets.only(left: 16, right: 8),
                              padding: const EdgeInsets.only(left: 16, right: 100),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(30),
                                color: const Color.fromRGBO(244, 244, 244, 1),
                              ),
                              child: TextField(
                                controller: _controller,
                                style: const TextStyle(fontSize: 14.0), // 设置字体大小
                                decoration: const InputDecoration(
                                  hintText: 'Haga clic para ingresar texto', // 默认提示文本
                                  border: InputBorder.none, // 去掉所有边框
                                ),
                                maxLines: null, // 设置为null以支持自动换行
                              ),
                            ),
                            Positioned(
                              right: 48,
                              bottom: 0,
                              
                              child: Container(
                                width: 48,
                                height: 48,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(30),
                                  color: const Color.fromRGBO(244, 244, 244, 1),
                                ),
                                // padding: const EdgeInsets.only(right: 16),
                                child: Center(
                                  child: IconButton(
                                    icon: const Icon(CupertinoIcons.shuffle, size: 18,),
                                    onPressed: (){
                                      Random random = Random();
                                      int randomNumber = random.nextInt(100); // nextInt(100) 生成 0 到 100 的随机数
                                      _controller.text = messageList[randomNumber]['text'];
                                      setState(() {
                                        curText = messageList[randomNumber]['text'];
                                      });
                                    },
                                  ),
                                ) ,
                              ) 
                            ),
                            Positioned(
                              right: 16,
                              bottom: 0,
                              
                              child: Container(
                                width: 48,
                                height: 48,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(30),
                                  color: const Color.fromRGBO(244, 244, 244, 1),
                                ),
                                child: Center(
                                  child: IconButton(
                                    icon: const Icon(CupertinoIcons.clear, size: 18,),
                                    onPressed: _clearInput,
                                  ),
                                ) ,
                              ) 
                            )
                          ],
                        )
                      ),
                      Container(
                        width: 48,
                        height: 48,
                        margin: const EdgeInsets.only(right: 16),
                        decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: InkWell(
                          onTap: () {
                            // setState(() {
                            //   isPainter = false;
                            //   (context as Element).markNeedsBuild();
                            // });
                            Navigator.pop(context);
                            // showStyleDialog(context);
                          },
                          child: const Icon(CupertinoIcons.check_mark, color: Colors.white,),
                        ),
                      ),

                    ],
                  ),
                  const SizedBox(height: 12,),
                  Expanded(child: 
                  SingleChildScrollView(
                    controller: controller,
                    child: Column(
                      children: [
                        for (var i = 0; i < messageList.length; i++)
                          InkWell(
                            onTap: () {
                              _controller.text = messageList[i]['text'];
                              setState(() {
                                curText = messageList[i]['text'];
                                textIndex = i;
                                (context as Element).markNeedsBuild();
                              });
                            },
                            child: Container(
                              margin: const EdgeInsets.only(top: 8, bottom: 8),
                              padding: const EdgeInsets.only(bottom: 8),
                              decoration: const BoxDecoration(
                                border: Border(
                                  bottom: BorderSide(
                                    width: .5,
                                    color: Color.fromRGBO(0, 0, 0, .1)
                                  )
                                )
                              ),
                              child: Row(
                                children: [
                                  const SizedBox(width: 12,),
                                  Container(
                                    width: 20,
                                    height: 20,
                                    decoration: BoxDecoration(
                                      color: Colors.black,
                                      borderRadius: BorderRadius.circular(10)
                                    ),
                                    
                                    child: Center(
                                      child: Text('${i+1}', style: const TextStyle(color: Colors.white, fontSize: 12), maxLines: 1, overflow: TextOverflow.ellipsis,),
                                    ) ,
                                  ),
                                  const SizedBox(width: 12,),
                                  Expanded(child: Text(messageList[i]['text'], style: TextStyle(color: textIndex == i ? const Color.fromARGB(255, 215, 31, 39) : Colors.black),))
                                  

                              ])
                            ),
                          ),                         
                      ],
                    ),
                  )
                  )
                  // Text(curCategoryDataList['sort'].toString()),
                  
                  
                ],
              ),
          )
        );
      },
    );
  }
  void showbgDialog(BuildContext context) {
    double height = MediaQuery.of(context).size.height; 
    double width = MediaQuery.of(context).size.width;

    showModalBottomSheet(
      isScrollControlled: true,
      backgroundColor: const Color.fromARGB(0, 153, 153, 153),
      barrierColor: Colors.transparent,
      context: context,
      builder: (BuildContext context) {
        return  
          Container(
            height: height * .5,
            width: width,
            // padding: const EdgeInsets.only(top: 12),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.3),
                  offset: const Offset(0, 3),
                  blurRadius: 10.0,
                ),
              ],
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              )
            ),
            
            child: SafeArea(child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Stack(
                    children: [
                      SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: Container(
                          padding: const EdgeInsets.only(right: 48),
                          // decoration: BoxDecoration(
                          //   gradient: LinearGradient(
                          //     colors: [
                          //       Colors.blue, // 渐变颜色1
                          //       Colors.purple, // 渐变颜色2
                          //     ],
                          //     begin: Alignment.topLeft, // 渐变开始位置
                          //     end: Alignment.bottomRight, // 渐变结束位置
                          //   ),
                          // ),
                          child: Row(
                            children: [
                              for(var index = 0; index < categoryList.length; index++)
                                GestureDetector(
                                  onTap: () {
                                    var curCategoryData = categoryList.firstWhere((item) => item['slug'] == categoryList[index]['slug'], orElse: () => null);
                                    setState(() {
                                      curSubIndex = categoryList[index]['slug'];
                                      curCategoryDataList = curCategoryData;
                                      (context as Element).markNeedsBuild();
                                    });

                                    print(curCategoryData);
                                    
                                  },
                                  child: Container(
                                    margin: const EdgeInsets.only(top: 12, left: 12, bottom: 12),
                                    padding: const EdgeInsets.only(right: 16, top: 6, bottom: 6),
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        SizedBox(
                                          width: 16,
                                          height: 16,
                                          child: Image.asset('images/category/${categoryList[index]['slug']}.webp'),
                                        ),
                                        const SizedBox(width: 4),
                                        Text(
                                          categoryList[index]['category'],
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontFamily: 'OpenSans',
                                            color: curSubIndex == categoryList[index]['slug'] ? Colors.red : Colors.black
                                          ),
                                        ),
                                        
                                      ],
                                    ),
                                  ),
                                ),
                              const SizedBox(width: 12,)
                            ]
                          ),
                        ) ,
                      ),
                      Positioned(
                        right: 0,
                        top: 14,
                        child: InkWell(
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Container(
                            decoration: const BoxDecoration(
                              gradient: LinearGradient(
                                colors: [
                                  Color.fromRGBO(255, 255, 255, .1), // 渐变颜色1
                                  Color.fromRGBO(255, 255, 255, .8), // 渐变颜色1
                                  Color.fromRGBO(255, 255, 255, 1), // 渐变颜色2
                                ],
                                begin: Alignment.topLeft, // 渐变开始位置
                                end: Alignment.bottomRight, // 渐变结束位置
                              ),
                              // borderRadius: BorderRadius.circular(15), // 可选：设置圆角
                            ),
                            padding: const EdgeInsets.only(left: 48, right: 16),
                            // color: Colors.white,
                            child: const Icon(CupertinoIcons.check_mark),
                          ) ,
                        )
                      )
                    ],
                  ),
                  
                  // Container(
                  //   padding: const EdgeInsets.only(left: 16, right: 16, top: 12),
                  //   child: Row(
                  //     children: [
                  //       Text('Imagen'),
                  //       const Spacer(),
                  //       InkWell(
                  //       onTap: () {
                  //         Navigator.pop(context);
                  //       },
                  //       child: const Icon(CupertinoIcons.check_mark),
                  //     )
                  //     ],
                  //   ),
                  // ),
                  // const SizedBox(height: 12,),
                  // Text(curCategoryDataList['sort'].toString()),
                  if(curCategoryDataList['sort'] != null)
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(left: 16, right: 16),
                        child: SingleChildScrollView(
                          controller: controller,
                          child: GridView.builder(
                            shrinkWrap: true, // 使 GridView 的高度适应内容
                            physics: const NeverScrollableScrollPhysics(), // 禁用 GridView 的滚动
                            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 4, // 每行放置 4 张图片
                              childAspectRatio: 1, // 宽高比
                              crossAxisSpacing: 8, // 交叉轴间距
                              mainAxisSpacing: 8, // 主轴间距
                            ),
                            itemCount: curCategoryDataList['sort'].length,
                            itemBuilder: (context, index) {
                              return InkWell(
                                onTap: () {
                                  setState(() {
                                    imgId = curCategoryDataList['sort'][index];
                                  });
                                },
                                child: Container(
                                  width: 100,
                                  height: 100,
                                  child: CachedNetworkImage(
                                    imageUrl: "https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/images-origin/$curSubIndex/${curCategoryDataList['sort'][index]}.webp?x-oss-process=image/resize,p_20",
                                    placeholder: (context, url) => const LoadingSpinner(), // 占位图
                                    errorWidget: (context, url, error) => const Icon(Icons.error), // 错误图标
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
                      ) 
                    ),
                ],
              ),
            ),
          )
        );
      },
    );
  }
}


class FontSelectionRow extends StatelessWidget {
  final Function(String) onFontSelected;
  final String selectedFont; // 新增选中的字体参数

  const FontSelectionRow({
    super.key,
    required this.onFontSelected,
    required this.selectedFont,
  });

  @override
  Widget build(BuildContext context) {
    final List<Map<String, String>> fonts = [
      {'name': 'Good Morning', 'font': 'Lobster'},
      {'name': 'Good Morning', 'font': 'DancingScript'},
      {'name': 'Good Morning', 'font': 'Jersey15'},
      {'name': 'Good Morning', 'font': 'Pacifico'},
      {'name': 'Good Morning', 'font': 'PlaywriteAUSA'},
      {'name': 'Good Morning', 'font': 'PlaywriteVN'},
      {'name': 'Good Morning', 'font': 'impact'},
      {'name': 'Good Morning', 'font': 'Inkfree'},
      {'name': 'Good Morning', 'font': 'Montserrat'},
      {'name': 'Good Morning', 'font': 'Ubuntu'},
      {'name': 'Good Morning', 'font': 'georgia'},
      {'name': 'Good Morning', 'font': 'OpenSans'},
    ];

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: fonts.map((font) {
          return _buildFontButton(font['name']!, font['font']!);
        }).toList(),
      ),
    );
  }

  Widget _buildFontButton(String displayName, String fontFamily) {
    return InkWell(
      onTap: () {
        onFontSelected(fontFamily);
      },
      child: Container(
        padding: const EdgeInsets.only(left: 12, right: 12, top: 6, bottom: 6),
        decoration: selectedFont == fontFamily
            ? BoxDecoration(
                color: const Color.fromARGB(255, 215, 31, 39),
                borderRadius: BorderRadius.circular(20),
              )
            : null,
        child: Text(
          displayName,
          style: TextStyle(
            fontFamily: fontFamily,
            color: selectedFont == fontFamily ? Colors.white : Colors.black,
          ),
        ),
      ),
    );
  }
}


class DashedBorderPainter extends CustomPainter {
  final Color borderColor; // 边框颜色

  // 构造函数，接受颜色参数
  DashedBorderPainter({this.borderColor = const Color.fromRGBO(0, 0, 0, 1)});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = borderColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.5;

    // 绘制虚线
    double dashWidth = 5.0;
    double dashSpace = 5.0;
    double startX = 0;

    // 上边
    while (startX < size.width) {
      canvas.drawLine(Offset(startX, 0), Offset(startX + dashWidth, 0), paint);
      startX += dashWidth + dashSpace;
    }

    startX = 0; // 重置起始位置

    // 右边
    while (startX < size.height) {
      canvas.drawLine(Offset(size.width, startX), Offset(size.width, startX + dashWidth), paint);
      startX += dashWidth + dashSpace;
    }

    startX = 0; // 重置起始位置

    // 下边
    while (startX < size.width) {
      canvas.drawLine(Offset(size.width - startX, size.height), Offset(size.width - startX - dashWidth, size.height), paint);
      startX += dashWidth + dashSpace;
    }

    startX = 0; // 重置起始位置

    // 左边
    while (startX < size.height) {
      canvas.drawLine(Offset(0, size.height - startX), Offset(0, size.height - startX - dashWidth), paint);
      startX += dashWidth + dashSpace;
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}